package com.luck.easyfoodbatch.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.custom.RoundedImageView;
import com.luck.easyfoodbatch.mvp.mine.UpdateMemberModel;
import com.luck.easyfoodbatch.mvp.mine.UpdateMemberPresenter;
import com.luck.easyfoodbatch.mvp.mine.UpdateMemberView;
import com.luck.easyfoodbatch.mvp.mine.UploadImageModel;
import com.luck.easyfoodbatch.mvp.mine.UploadImageView;
import com.luck.easyfoodbatch.mvp.mine.UploadSinglePresenter;
import com.luck.easyfoodbatch.mvp.model.MemberModel;
import com.luck.easyfoodbatch.mvp.model.UploadModel;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.PictureConfig;
import com.yalantis.ucrop.entity.LocalMedia;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PersonalActivity extends BaseActivity implements UploadImageView, UpdateMemberView {
    private final String TAG = "PersonalActivity";
    private List<LocalMedia> photoInfos = new ArrayList<>();
    @BindView(R.id.right_title)
    TextView rightTitle;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.riv_avatar)
    RoundedImageView rivAvatar;
    @BindView(R.id.rl_avatar)
    RelativeLayout rlAvatar;
    @BindView(R.id.et_uname)
    EditText et_uname;
    @BindView(R.id.rl_username)
    RelativeLayout rlUsername;
    private UploadImageModel imageModel;
    private String avatar = "";
    private UpdateMemberModel memberModel;
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    protected static final int REQUEST_STORAGE_READ_ACCESS_CAMERA = 102;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal, "头像昵称", "保存", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        initInfo(false);
        if (ContextCompat.checkSelfPermission(PersonalActivity.this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.CAMERA,
                    getString(R.string.mis_permission_camera),
                    REQUEST_STORAGE_READ_ACCESS_CAMERA);
        }
    }

    /**
     * 设置个人信息
     */
    private void initInfo(boolean isLoading) {
        if (user != null) {
            if (!Tools.isNull(user.getNickname())) {
                et_uname.setText(user.getNickname());
            } else {
                et_uname.setText("");
            }
            if (!isLoading) {
                avatar = user.getAvatar_path();
                if (!Tools.isNull(avatar)) {
                    String path = HttpUtil.IMG_BASE_URL + user.getAvatar_path();
                    Glide.with(getApplicationContext())
                            .load(path)
                            .centerCrop()
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(rivAvatar);
                } else {
                    rivAvatar.setImageResource(R.mipmap.camera);
                }
            }
        }
    }

    @OnClick({R.id.right_title, R.id.rl_avatar})
    public void onClick(View view) {
        String nickname = et_uname.getText().toString().trim();
        switch (view.getId()) {
            case R.id.right_title:
                showProgressDialog("正在修改，请稍候……");
                memberModel = new UpdateMemberPresenter(this, mContext);
                memberModel.updateMemberInfo(nickname, avatar);
                break;
            case R.id.rl_avatar:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                        && ActivityCompat.checkSelfPermission(PersonalActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                            getString(R.string.mis_permission_rationale),
                            REQUEST_STORAGE_READ_ACCESS_PERMISSION);
                } else {
                    FunctionConfig options = new FunctionConfig();
                    options.setCompress(true);
                    options.setSelectMode(FunctionConfig.MODE_SINGLE);
                    PictureConfig.init(options);
                    PictureConfig.getPictureConfig().openPhoto(PersonalActivity.this,resultCallback);
                }

                break;
        }
    }

    private void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            new AlertDialog.Builder(this)
                    .setTitle("获取相册权限")
                    .setMessage(rationale)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(PersonalActivity.this, new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create().show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_STORAGE_READ_ACCESS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                FunctionConfig options = new FunctionConfig();
                options.setCompress(true);
                options.setSelectMode(FunctionConfig.MODE_SINGLE);
                PictureConfig.init(options);
                PictureConfig.getPictureConfig().openPhoto(PersonalActivity.this,resultCallback);
            }
        } else if (requestCode == REQUEST_STORAGE_READ_ACCESS_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    @Override
    public void uploadSuccess(UploadModel model) {
        if (model.getStatus() == HttpUtil.RESULT_OK) {
            List<String> data = model.getData();
            if (data != null && data.size() > 0) {
                avatar = data.get(0);
            }
        } else {
            T.showToast(mContext, model.getMsg());
        }

    }

    @Override
    public void httpStatusError() {

    }


    @Override
    public void updateMemberSuccess(MemberModel model) {
        if (model.getStatus() == HttpUtil.RESULT_OK) {
            MemberModel.DataBean data = model.getData();
            if (user != null) {
                user.setNickname(data.getNickname());
                user.setAvatar_path(data.getAvatar_path());
                App.getInstance().saveObject(user, HttpUtil.USER_KEY);
            }
            initInfo(true);
            finish();
        } else {
            T.showToast(mContext, model.getMsg());
        }
    }


    @Override
    public void hideLoading() {
        hideShowProgress();
    }

    @Override
    public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
        Log.i("上传进度", (int) (progress * 100) + "%");
    }

    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> list) {
            photoInfos = list;
            if (photoInfos != null || photoInfos.size() > 0) {
                showProgressDialog("正在上传，请稍候……");
                LocalMedia media = photoInfos.get(0);
                File file;
                if (media.isCompressed()) {
                    file = new File(media.getCompressPath());
                } else {
                    file = new File(media.getPath());
                }
                Glide.with(getApplicationContext())
                        .load(file)
                        .asBitmap().centerCrop()
                        .placeholder(R.mipmap.camera)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(rivAvatar);

                imageModel = new UploadSinglePresenter(PersonalActivity.this, mContext);
                imageModel.uploads(0, file, null);

            }
        }
    };
}
